package com.china.api.wechat.server;

import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.QueryStringDecoder;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.china.api.wechat.processor.main.Delegate;


public class HttpSnoopServerHandler extends SimpleChannelUpstreamHandler {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private final StringBuilder buf = new StringBuilder();
	
	private Delegate delegate = new Delegate();

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		HttpRequest request = (HttpRequest) e.getMessage();

		HttpMethod method = request.getMethod();
		QueryStringDecoder queryStringDecoder = new QueryStringDecoder(
				request.getUri());
		Map<String, List<String>> params = queryStringDecoder.getParameters();
		if (method.compareTo(HttpMethod.GET) == 0) {// 响应腾讯的验证请求
			for (Entry<String, List<String>> p : params.entrySet()) {
				String key = p.getKey();
				if (key.equals("echostr")) {
					List<String> vals = p.getValue();
					for (String val : vals) {
						buf.append(val);
					}
				} else {
					List<String> vals = p.getValue();
					for (String val : vals) {
						logger.debug(key + ":" + val);
					}

				}
			}
			buf.append("\r\n");
		} else {// 处理后续腾讯转发过来的用户发送的内容
			ChannelBuffer content = request.getContent();
			if (content.readable()) {
				String strContent = content.toString(CharsetUtil.UTF_8);
				logger.debug("post:" + strContent);
				String s = delegate.process(strContent);
				buf.append(s);
			}
		}
		writeResponse(e);

	}

	private void writeResponse(MessageEvent e) {
		HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
		response.setContent(ChannelBuffers.copiedBuffer(buf.toString(),
				CharsetUtil.UTF_8));
		response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
		ChannelFuture future = e.getChannel().write(response);
		future.addListener(ChannelFutureListener.CLOSE);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		e.getCause().printStackTrace();
		e.getChannel().close();
	}
}
